package com.wise.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.wise.pojo.MsgConstants;
import com.wise.pojo.MsgLog;
import com.wise.pojo.Person;
import com.wise.service.IMsgLogService;
import com.wise.service.IPersonService;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author rzc
 * @date 2021/9/22
 */
@Component
public class PersonTask {
    @Autowired
    private IMsgLogService msgLogService;
    @Autowired
    private IPersonService personService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 每10秒执行一次
     */
    @Scheduled(cron = "0/10 * * * * ?")
    public void  mailTask(){
        //查询投递表中未投递成功并且达到重发时间的记录
        List<MsgLog> list = msgLogService.list(new QueryWrapper<MsgLog>().eq("status", 0).lt("tryTime", LocalDateTime.now()));
        //更新上述记录 重发次数+1 重发时间设为当前时间+1分钟  更新时间
        for (MsgLog msgLog : list) {
            //投递次数大于3次时，设置记录为投递失败
            if(3<=msgLog.getCount()){
                msgLogService.update(new UpdateWrapper<MsgLog>().set("status",2).eq("msgId",msgLog.getMsgId()));
            }else {
                //投递次数小于3次时，重发消息
                msgLogService.update(new UpdateWrapper<MsgLog>().set("count",msgLog.getCount()+1).
                        set("tryTime", LocalDateTime.now().plusMinutes(MsgConstants.MSG_TIMEOUT)).eq("msgId",msgLog.getMsgId()));
                Person person = personService.getById(msgLog.getPid());
                //发送消息
                rabbitTemplate.convertSendAndReceive(MsgConstants.MAIL_EXCHANGE_NAME,MsgConstants.MAIL_ROUTING_KEY_NAME,person,new CorrelationData(msgLog.getMsgId()));
            }

        }

    }
}
